package cn.edu.lzzy.controllers;

import cn.edu.lzzy.entities.User;
import cn.edu.lzzy.services.UserService;
import cn.edu.lzzy.utils.AuthUtils;
import cn.edu.lzzy.utils.FileUtils;
import cn.edu.lzzy.utils.StringUtils;
import cn.edu.lzzy.vm.JSONResult;
import cn.edu.lzzy.vm.VmUser;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.oas.annotations.EnableOpenApi;


import java.util.UUID;
@EnableOpenApi
@Tag(name="authenticate-controller",description = "包含用户注册/登录/查重功能")
@RestController
public class AuthenticateController {
    private final UserService userService;

    @Value("${user.picPath}")
    private String imgPath;



    @Autowired
    public AuthenticateController(UserService userService){
        this.userService=userService;
    }
    /**
     * 用户注册
     * 当前开发方式；前后端分离
     * 数据传输方式: JSON
     * 传入参数:
     * 返回参数：
     */
    @Operation(summary = "用户注册功能,调用方法")
    @Parameters(@Parameter(description = "入口参数User对象的JSON数据"))
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public JSONResult register(@RequestBody JSONObject json){
        String nickName=json.getString("nickName");
        String userName=json.getString("userName");
        String email=json.getString("email");
        String phone=json.getString("phone");
        String password=json.getString("password");
        String avatar=json.getString("avatar");
        boolean applyTeacher=json.getBoolean("applyTeacher");

        if(StringUtils.isEmpty(nickName)){
            nickName=userName;
        }
        if(StringUtils.isEmpty(nickName) || StringUtils.isEmpty(userName)
        || StringUtils.isEmpty(email) || StringUtils.isEmpty(phone)
        || StringUtils.isEmpty(password) || StringUtils.isEmpty(avatar)){
            return new JSONResult(413,null,"信息不完整，无法注册！");
        }

        if(!StringUtils.validMail(email)){
            return new JSONResult(417,null,"非法的Email数据格式");
        }
        //与Email 类似实现，还有Phone
        if(!StringUtils.validPhone(phone)){
            return new JSONResult(417,null,"非法的phone数据格式");
        }
        //用户查重
        if(userService.isUserNameOccupied(userName)){
            return new JSONResult(409,null,"用户账号已被占用，请重新申请");
        }
        String salt= UUID.randomUUID().toString();
        User user = new User();
        user.setNickName(nickName);
        user.setUserName(userName);
        user.setEmail(email);
        user.setPhone(phone);
        user.setPassword(StringUtils.md5Encode(password,salt));//将password进行MD5加密
        user.setAvatar(avatar);
        user.setApplyTeacher(applyTeacher);
        user.setType(0);//将学生作为用户默认权限
        user.setSalt(salt);//记录随机加盐数值

        VmUser vm= VmUser.apiLogin(userService.register(user));
        return new JSONResult(200,vm,"用户注册成功");
    }

    /****
     * 用户登录
     * 当前开发方式：前后端分离
     * 数据传方式：JSON’
     * 调用：HTTP POST
     * Parameter:json 数据
     * Return：http状态码
     */
    @Operation(summary = "用户登录功能，调用方法名")
    @PostMapping(value = "/login",produces = "application/json")
    public JSONResult login(@RequestBody JSONObject json){
        String userName=json.getString("userName");
        String password=json.getString("password");
        String salt=userService.getSalt(userName);
        User user=userService.checkedUser(userName,StringUtils.md5Encode(password,salt));
        if(user==null){
            return new JSONResult(401,null,"用户或密码错误，请检查后重新登录");
        }
        if(user.getType()<0){
            return new JSONResult(403,null,"非授权访问！！");
        }
        VmUser vm=VmUser.apiLogin(user);
        return new JSONResult(200,vm,"登录成功！");
    }
    @Operation(summary = "用户注销功能,调用方法名：")
   @PostMapping(value = "/logout")//
    public JSONResult logout(@RequestParam String token){
        return new JSONResult(200, AuthUtils.logout(token),"注销成功");
   }
    //检查用户占用情况
    @GetMapping(value = "/exist/{user}")
    public JSONResult isUserExist(@PathVariable String user){
        boolean exist=userService.isUserNameOccupied(user);
        String msg=exist? "用户名已被占用！":"用户名未被注册";
        return new JSONResult(null,msg);
    }

    @Operation(summary = "用户头像上传功能")
    @PostMapping(value = "uploadImage")
    public JSONResult upload(@RequestParam MultipartFile file){
        JSONObject result= FileUtils.uploadWithRandomName(file,imgPath);
        if(FileUtils.UPLOAD_PARAM_STATUS=="false"){
            return new JSONResult(134,result.getString(FileUtils.UPLOAD_PARAM_URL),result.getString(FileUtils.UPLOAD_PARAM_MESSAGE));
        }
        return  new JSONResult(301,result.getString(FileUtils.UPLOAD_PARAM_URL),result.getString(FileUtils.UPLOAD_PARAM_MESSAGE));
    }



}
